package cn.smbms.controller;

import cn.smbms.pojo.Provider;
import cn.smbms.pojo.User;
import cn.smbms.service.provider.ProviderService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/provider")
public class ProviderController {
    private Logger logger = Logger.getLogger(UserController.class);
    @Resource
    private ProviderService providerService;

    @RequestMapping(value = "/providerlist.html")
    public String getProviderList(Model model,
                              @RequestParam(value="proName",required=false) String proName,
                              @RequestParam(value="proCode",required=false) String proCode,
                              @RequestParam(value="pageIndex",required=false) String pageIndex){
        logger.info("getProviderList ---- > proName：" + proName);
        logger.info("getProviderList ---- > queryUserRole：" + proCode);
        logger.info("getProviderList ---- > pageIndex：" + pageIndex);
        int _queryUserRole = 0;
        List<Provider> providerList = null;
        //设置页面容量
        int pageSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;

        if(proName == null){
            proName = "";
        }
        if(pageIndex != null){
            currentPageNo = Integer.valueOf(pageIndex);
        }
        //总数量（表）
        int totalCount	= providerService.getProviderCount(proName,proCode);
        //总页数
        PageSupport pages=new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();

        //控制首页和尾页
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }
        providerList = providerService.getProviderList(proName,proCode,currentPageNo,pageSize);
        model.addAttribute("providerList", providerList);
        model.addAttribute("proName", proName);
        model.addAttribute("proCode", proCode);
        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("currentPageNo", currentPageNo);
        return "providerlist";
    }

    @RequestMapping(value = "/provideradd.html",method = RequestMethod.GET)
    public String addProvider(@ModelAttribute("provider") Provider provider){
        return "provideradd";
    }

    @RequestMapping(value = "/addsave.html",method = RequestMethod.POST)
    public String addProviderSave(Provider provider,
                                  HttpSession session,
                                  HttpServletRequest request,
                                  @RequestParam(value = "attachs",required = false) MultipartFile[] attachs){
        String companyLicPicPath = null;
        String orgCodePicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
        logger.info("uploadFile path ============== > "+path);
        for (int i = 0;i < attachs.length;i++){
            MultipartFile attach = attachs[i];
            if(!attach.isEmpty()){
                if(i==0){
                    errorInfo = "uploadClError";
                }else if (i==1){
                    errorInfo = "uploadOcError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                String prefix = FilenameUtils.getExtension(oldFileName);//原文件名后缀
                int filesize = 5000000;
                if (attach.getSize() > filesize){//上传大小不得超过 500k
                    request.setAttribute(errorInfo, " * 上传大小不得超过 500k");
                    flag = false;
                }else if (prefix.equalsIgnoreCase("jpg")
                        || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg")
                        || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
                    String fileName = System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"_Provider.jpg";
                    File targetFile = new File(path,fileName);
                    if (!targetFile.exists()){
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(targetFile);
                    }catch (Exception e){
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败！");
                        flag = false;
                    }
                    if (i==0){
                        companyLicPicPath = path+File.separator+fileName;
                    }else if (i==1){
                        orgCodePicPath = path+File.separator+fileName;
                    }
                    logger.debug("companyLicPicPath：" + companyLicPicPath);
                    logger.debug("orgCodePicPath：" + orgCodePicPath);
                }else{
                    request.setAttribute("uploadClError", " * 上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if (flag){
            provider.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
            provider.setCreationDate(new Date());
            provider.setCompanyLicPicPath(companyLicPicPath);
            provider.setOrgCodePicPath(orgCodePicPath);
            if(providerService.add(provider)){
                return  "redirect:/provider/providerlist.html";
            }
        }
        return "provideradd";
    }

    @RequestMapping(value = "/view/{id}",method = RequestMethod.GET)
    public String view(@PathVariable Integer id, Model model){
        logger.debug("view id====================" + id);
        Provider provider = providerService.getProviderById(id);
        model.addAttribute(provider);
        return "providerview";
    }

    @RequestMapping(value = "/providermodify.html",method = RequestMethod.GET)
    public String getProviderById(@RequestParam Integer proid,Model model){
        logger.debug("getProviderById proid===================== "+proid);
        Provider provider = providerService.getProviderById(proid);
        model.addAttribute(provider);
        return "providermodify";
    }

    @RequestMapping(value = "/providermodifysave.html",method = RequestMethod.POST)
    public String modifyProviderSave(Provider provider,HttpSession session){
        logger.debug("modifyProviderSave providerid=========" + provider.getId());
        provider.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        provider.setModifyDate(new Date());
        if(providerService.update(provider)){
            return  "redirect:/provider/providerlist.html";
        }
        return "providermodify";
    }

}
